/**
 * 配置界面的js逻辑
 */

// 读取设置
function loadSettings() {
    const apiKey = localStorage.getItem('apiKey');
    const model = localStorage.getItem('model');
    const maxConcurrent = localStorage.getItem('maxConcurrent');
    const apiEndpoint = localStorage.getItem('apiEndpoint');
    
    if (apiKey) {
        document.getElementById('api-key').value = apiKey;
    }
    if (model) {
        document.getElementById('model').value = model;
    }
    if (maxConcurrent) {
        document.getElementById('max-concurrent').value = maxConcurrent;
    }
    if (apiEndpoint) {
        document.getElementById('api-endpoint').value = apiEndpoint;
    }
}

// 保存设置
function saveSettings() {
    const apiKey = document.getElementById('api-key').value;
    const model = document.getElementById('model').value;
    const maxConcurrent = document.getElementById('max-concurrent').value;
    let apiEndpoint = document.getElementById('api-endpoint').value;

    // 检查 API Endpoint 是否为空，如果为空则恢复到默认值
    if (apiEndpoint.trim() === '') {
        apiEndpoint = 'https://api.anthropic.com/v1/messages';
    }

    localStorage.setItem('apiKey', apiKey);
    localStorage.setItem('model', model);
    localStorage.setItem('maxConcurrent', maxConcurrent);
    localStorage.setItem('apiEndpoint', apiEndpoint);
}

// 取消设置
function cancelSettings() {
    // 清空测试连接结果
    resultElement.textContent = '';
    resultElement.style.display = 'none';

    // 恢复 spinner 的显示状态
    if (spinner) {
        spinner.style.display = 'none';
    } else {
        console.error('无法获取 spinner 元素');
    }
    testConnectionButton.textContent = '测试连接';
    testConnectionButton.disabled = false;

    // 关闭弹窗
    if (settingsModal) {
        settingsModal.style.display = 'none';
    } else {
        console.error('无法获取 settings-modal 元素');
    }
}

// 点击保存设置
document.getElementById('save-settings').addEventListener('click', saveSettings);

// 配置
const settingsButton = document.getElementById('settings-button');
const settingsModal = document.getElementById('settings-modal');
const saveSettingsButton = document.getElementById('save-settings');
const cancelSettingsButton = document.getElementById('cancel-settings');
const testConnectionButton = document.getElementById('test-connection');
const resultElement = document.getElementById('test-connection-result');
const spinner = document.getElementById('spinner-id')
if (!spinner) {
    console.error('无法获取 spinner 元素');
}

settingsButton.addEventListener('click', function() {
    settingsModal.style.display = 'block';
});

// 配置页：保存按钮
saveSettingsButton.addEventListener('click', function() {
    saveSettings();
    settingsModal.style.display = 'none';
});

window.addEventListener('click', function(event) {
    if (event.target == settingsModal) {
        cancelSettings();
    }
});

// 配置页：取消按钮
cancelSettingsButton.addEventListener('click', function() {
    console.log('取消按钮被点击');
    cancelSettings();
});

// 配置页：测试连接按钮
testConnectionButton.addEventListener('click', async function() {
    const apiKey = document.getElementById('api-key').value;
    const model = document.getElementById('model').value;
    const apiEndpoint = document.getElementById('api-endpoint').value;
    const originalText = this.textContent; // 保存按钮原始文字

    if (!apiKey || !model || !apiEndpoint) {
        alert('请先填写 API Key、模型和 API Endpoint');
        return;
    }

    // 显示加载图标
    resultElement.style.display = 'none';
    spinner.style.display = 'inline-block';
    this.textContent = '连接中'; // 清空按钮文本
    this.disabled = true; // 禁用按钮

    try {
        const response = await fetch('/api/test', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                api_key: apiKey,
                model: model,
                api_endpoint: apiEndpoint
            })
        });
        

        if (response.ok) {
            resultElement.style.display = 'block';
            resultElement.textContent = '连接成功！';
            resultElement.classList.add('success');
            resultElement.classList.remove('error');
        } else {
            const errorData = await response.json();
            const errorMessage = errorData.error;
            resultElement.style.display = 'block';
            resultElement.textContent = `连接失败：${errorMessage}`;
            resultElement.classList.add('error');
            resultElement.classList.remove('success');
        }
    } catch (error) {
        resultElement.style.display = 'block';
        resultElement.textContent = `连接出错：${error.message}`;
    } finally {
        // 隐藏加载图标并恢复按钮文字
        spinner.style.display = 'none';
        this.textContent = originalText;
        this.disabled = false; // 启用按钮
    }
});
